//商品详情展示
function showDetail(goodsId) {
    $.ajax({
        url : "goods/query/normal",
        async : true,
        type : "GET",
        data : {
            "goodsId" : goodsId
        },
        // 成功后开启模态框
        success : queryDetail,
        error : function(res) {
            alert("商品信息获取失败");
        },
        dataType : "json"
    });
}
function queryDetail(res) {
    if(res.code!=0){
        alert(res.msg);
    }
    var model = res.data;
    $("#d_goodsName").text(model.goodsName);
    $("#d_goodsParam").text(model.goodsParam);
    $("#d_goodsPic").attr('src',model.goodsPic);
    $("#d_goodsPrice").text(model.goodsPrice);
    var typeName;
    switch (model.goodsType) {
        case 1: typeName="食品/保健类"; break;
        case 2: typeName="服饰类"; break;
        case 3: typeName="皮具箱包类"; break;
        case 4: typeName="珠宝饰品类"; break;
        case 5: typeName="母婴/儿童类"; break;
        case 6: typeName="家电类"; break;
        case 7: typeName="数码类"; break;
        case 8: typeName="汽车配件类"; break;
        case 9: typeName="家具/建材类"; break;
        case 10: typeName="图书影音类"; break;
        default: typeName="不限";
    }
    $("#d_goodsType").text(typeName);
    $("#d_goodsStock").text(model.goodsStock);
    $("#d_goodsSales").text(model.goodsSales);
    $("#d_shopName").text(model.shopName);
    $("#d_goodsAddr").text(model.goodsAddr);
    $("#d_goodsTime").text(model.goodsTime);
    $("#d_modifyTime").text(model.modifyTime);

    if(model.isOnsale==0){
        $("#d_isOnsale").addClass("label-default");
    }else{
        $("#d_isOnsale").addClass("label-success");
    }
    if(model.isSeckill==0){
        $("#d_isSeckill").addClass("label-default");
    }else{
        $("#d_isSeckill").addClass("label-success");
    }
    if(model.isAuction==0){
        $("#d_isAuction").addClass("label-default");
    }else{
        $("#d_isAuction").addClass("label-success");
    }
    // 显示模态框
    $('#detailModal').modal('show');
}

//商品编辑展示
function showEdit(goodsId) {
    $.ajax({
        url : "goods/query/normal",
        async : true,
        type : "GET",
        data : {
            "goodsId" : goodsId
        },
        // 成功后开启模态框
        success : queryEdit,
        error : function(res) {
            alert("连接失败");
        },
        dataType : "json"
    });
}
function queryEdit(res) {
    if(res.code!=0){
        alert(res.msg);
    }
    var model = res.data;
    $("#e_goodsId").val(model.goodsId);
    $("#e_goodsName").val(model.goodsName);
    $("#e_goodsParam").val(model.goodsParam);
    $("#e_goodsPrice").val(model.goodsPrice);
    $("#e_goodsType").val(model.goodsType);
    $("#e_goodsStock").val(model.goodsStock);
    $("#e_address").val(model.goodsAddr);
    $("#e_lnglat").val(model.goodsLng+','+model.goodsLat);
    $("#e_shopId").empty();
    for(var i in model.shopList){
        $("#e_shopId").append("<option value="+model.shopList[i].shopId+">"+model.shopList[i].shopName+"</option>");
    }
    $("#e_shopId").val(model.shopId);

    //显示地图
    var map = new AMap.Map('mapContainer', {
        zoom:11,//级别
        center: [model.goodsLng, model.goodsLat],//中心点坐标
    });
    //实例化点标记
    var marker = new AMap.Marker({
        position:[model.goodsLng, model.goodsLat]//位置
    })
    map.add(marker);
    //地址经纬度转换
    var geocoder = new AMap.Geocoder();
    function geoCode() {
        var address  = $('#e_address').val();
        geocoder.getLocation(address, function(status, result) {
            if (status === 'complete'&&result.geocodes.length) {
                var lnglat = result.geocodes[0].location
                document.getElementById('e_lnglat').value = lnglat;
                marker.setPosition(lnglat);
                map.add(marker);
                map.setFitView(marker);
            }else{
                alert("请输入正确地址！");
            }
        });
    }
    document.getElementById("geoButton").onclick = geoCode;
    document.getElementById("e_address").onkeydown = function(e) {
        if (e.keyCode === 13) {
            geoCode();
            return false;
        }
        return true;
    };
    //为地图注册click事件获取鼠标点击出的经纬度坐标
    var clickEventListener = map.on('click', function(e) {
        document.getElementById("e_lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat();
        if (marker) {
            marker.setMap(null);
            marker = null;
        }
        addMarker(e.lnglat.getLng(),e.lnglat.getLat());
        //这边是数组
        var lnglatXY=[e.lnglat.getLng(),e.lnglat.getLat()];
        regeocoder(lnglatXY);
    });
    //更改点标记位置
    function addMarker(lng,lat) {
        marker = new AMap.Marker({
            icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            position: [lng, lat]
        });
        marker.setMap(map);
    }
    //坐标-->地址
    function regeocoder(lnglatXY) {  //逆地理编码
        var geocoder = new AMap.Geocoder({
            radius: 100,
            extensions: "all"
        });
        geocoder.getAddress(lnglatXY, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                geocoder_CallBack(result);
            }
        });
    }
    function geocoder_CallBack(data) {
        var address = data.regeocode.formattedAddress; //返回地址描述
        document.getElementById("e_address").value=address;
    }


    // 显示模态框
    $('#editModal').modal('show');
}

//商品编辑提交
$("#editButton").click(function () {
    var data = new FormData(document.getElementById("editForm"));
    $.ajax({
        type: 'post',
        url: 'goods/modify/normal',
        dataType: 'json',
        data: data,
        contentType: false, //不设置内容类型
        processData: false, //不处理数据
        error: function(request) {
            alert("未知错误，请检查输入格式！");
        },
        success: function(res) {
            if(res.code==0) {
                alert("修改商品信息成功！");
                window.location.reload();
            }else{
                alert(res.msg);
            }
        }
    });
});

//商品下架
function showUnder(goodsId) {
    if (confirm("商品下架后可从下架商品栏中查看，并重新上架。\n\r是否确认下架该商品？")) {
        $.ajax({
            type: 'get',
            url: 'goods/upper/normal',
            dataType: 'json',
            data: {
                "goodsId": goodsId,
                "isUpper": 0
            },
            contentType: false, //不设置内容类型
            error: function (request) {
                alert("未知错误，下架失败");
            },
            success: function (res) {
                if (res.code == 0) {
                    alert("下架商品成功！");
                    window.location.reload();
                } else {
                    alert(res.msg);
                }
            }
        });
    }
}

//商品删除
function showDelete(goodsId) {
    if (confirm("请慎重删除商品，建议选择下架或编辑。\n\r是否确认删除该商品？")) {
        $.ajax({
            type: 'get',
            url: 'goods/delete/normal',
            dataType: 'json',
            data: {
                "goodsId": goodsId
            },
            contentType: false, //不设置内容类型
            error: function (request) {
                alert("未知错误，删除失败");
            },
            success: function (res) {
                if (res.code == 0) {
                    alert("删除商品成功！");
                    window.location.reload();
                } else {
                    alert(res.msg);
                }
            }
        });
    }
}

//商品添加展示
function showAdd() {
    $.ajax({
        url : "goods/shoplist",
        async : true,
        type : "GET",
        // 成功后开启模态框
        success : queryAdd,
        error : function(res) {
            alert("连接失败");
        },
        dataType : "json"
    });
}
function queryAdd(res) {
    if(res.code!=0){
        alert(res.msg);
    }
    //展示商家列表
    var shopList = res.data;
    $("#a_shopId").empty();
    for(var i in shopList){
        $("#a_shopId").append("<option value="+shopList[i].shopId+">"+shopList[i].shopName+"</option>");
    }
    //选择商家后填充地址
    $("#a_shopId").change(function(){
        var shopId = $("#a_shopId").val();
        for(var i in shopList){
            if(shopList[i].shopId==shopId){
                $("#a_lnglat").val(shopList[i].shopLng+','+shopList[i].shopLat);
                $("#a_address").val(shopList[i].shopAddr);
            }
        }
    });

    /**
     *地图模块
     */
    //显示地图
    var map = new AMap.Map('a_mapContainer', {
        zoom:11,//级别
        center: [120.2, 30.3],//中心点坐标
    });
    // 实例化点标记
    var marker = new AMap.Marker({
        position:[120.2, 30.3]
    })
    //地址经纬度转换
    var geocoder = new AMap.Geocoder();
    function geoCode() {
        var address  = $('#a_address').val();
        geocoder.getLocation(address, function(status, result) {
            if (status === 'complete'&&result.geocodes.length) {
                var lnglat = result.geocodes[0].location
                document.getElementById('a_lnglat').value = lnglat;
                marker.setPosition(lnglat);
                map.add(marker);
                map.setFitView(marker);
            }else{
                log.error('根据地址查询位置失败');
            }
        });
    }
    document.getElementById("a_geoButton").onclick = geoCode;
    document.getElementById("a_address").onkeydown = function(e) {
        if (e.keyCode === 13) {
            geoCode();
            return false;
        }
        return true;
    };
    //为地图注册click事件获取鼠标点击出的经纬度坐标
    var clickEventListener = map.on('click', function(e) {
        document.getElementById("a_lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat();
        if (marker) {
            marker.setMap(null);
            marker = null;
        }
        addMarker(e.lnglat.getLng(),e.lnglat.getLat());
        //这边是数组
        var lnglatXY=[e.lnglat.getLng(),e.lnglat.getLat()];
        regeocoder(lnglatXY);
    });
    //更改点标记位置
    function addMarker(lng,lat) {
        marker = new AMap.Marker({
            icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            position: [lng, lat]
        });
        marker.setMap(map);
    }
    //坐标-->地址
    function regeocoder(lnglatXY) {  //逆地理编码
        var geocoder = new AMap.Geocoder({
            radius: 100,
            extensions: "all"
        });
        geocoder.getAddress(lnglatXY, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                geocoder_CallBack(result);
            }
        });
    }
    function geocoder_CallBack(data) {
        var address = data.regeocode.formattedAddress; //返回地址描述
        document.getElementById("a_address").value=address;
    }

    // 显示模态框
    $('#addModal').modal('show');
}

//商品添加提交
$("#addButton").click(function () {
    var data = new FormData(document.getElementById("addForm"));
    //判断是否为空
    if(data.get('goodsName')===null||data.get('goodsName')===undefined||data.get('goodsName')==''||
        data.get('goodsParam')===null||data.get('goodsParam')===undefined||data.get('goodsParam')==''||
        data.get('goodsType')===null||data.get('goodsType')===undefined||data.get('goodsType')==''||
        data.get('shopId')===null||data.get('shopId')===undefined||data.get('shopId')==''||
        data.get('goodsPrice')===null||data.get('goodsPrice')===undefined||data.get('goodsPrice')==''||
        data.get('goodsStock')===null||data.get('goodsStock')===undefined||data.get('goodsStock')==''||
        data.get('file')===null||data.get('file')===undefined||data.get('file')==''||
        data.get('isUpper')===null||data.get('isUpper')===undefined||data.get('isUpper')==''){
        alert("数据不能为空，请检查。");
        return 0;
    }
    $.ajax({
        type: 'post',
        url: 'goods/add/normal',
        dataType: 'json',
        data: data,
        contentType: false, //不设置内容类型
        processData: false, //不处理数据
        error: function(request) {
            alert("未知错误，请检查输入格式！");
        },
        success: function(res) {
            if(res.code==0) {
                alert("添加商品成功！");
                window.location.reload();
            }else{
                alert(res.msg);
            }
        }
    });
});

//商品详情编辑展示
function showText(goodsId) {
    $("#t_goodsId").val(goodsId);
    $.ajax({
        url : "goods/text/show",
        async : true,
        type : "GET",
        data : {
            "goodsId" : goodsId
        },
        success : queryText,
        error : function(res) {
            alert("连接失败");
        },
        dataType : "json"
    });
}
function queryText(res) {
    if(res.code!=0){
        alert(res.msg);
    }
    editor.txt.html(res.data);
    // 显示模态框
    $('#textModal').modal('show');
}

//商品详情修改提交
$("#textButton").click(function () {
    var text = editor.txt.html();
    var formdata = new FormData();
    formdata.append('goodsDetail', text);
    formdata.append("goodsId", $("#t_goodsId").val());
    $.ajax({
        type: "POST",
        url:"goods/text/modify",
        data:formdata,	// 序列化表单值
        processData:false,
        contentType:false,
        error: function(request) {
            alert("未知错误！");
        },
        success: function(res) {
            if(res.code==0) {
                alert("修改商品详情成功！");
                window.location.reload();
            }else{
                alert(res.msg);
            }
        }
    });
});


//销售额展示
function showSales(goodsId) {
    $.ajax({
        url : "sales/goods",
        async : true,
        type : "GET",
        data : {
            "goodsId" : goodsId
        },
        // 成功后开启模态框
        success : function(res){
            if(res.code!=0){
                alert(res.msg);
            }
            var model = res.data;
            $("#s_id").val(model.id);
            $("#s_name").text(model.name);
            $("#s_yearSale").text(model.yearSale +' 元');
            $("#s_monthSale").text(model.monthSale +' 元');
            $("#s_weekSale").text(model.weekSale +' 元');
            $("#s_daySale").text(model.daySale +' 元');
            //显示模态框
            $('#salesModal').modal('show');
        },
        error : function(res) {
            alert("销量信息获取失败");
        },
        dataType : "json"
    });
}


//查询时间段销售额
$("#saleButton").click(function () {
    var formdata = new FormData(document.getElementById("salesForm"));
    $.ajax({
        type: "POST",
        url:"sales/goods/search",
        data:formdata,	// 序列化表单值
        processData:false,
        contentType:false,
        error: function(request) {
            alert("未知错误！");
        },
        success: function(res) {
            if(res.code==0) {
                $("#s_sale").text(res.data +' 元');
            }else{
                alert(res.msg);
            }
        }
    });
});